package br.org.acessobrasil.portal.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import br.org.acessobrasil.portal.modelo.Arquivo;
import br.org.acessobrasil.portal.persistencia.ArquivoDao;
import br.org.acessobrasil.portal.persistencia.ArquivoDaoSpring;

/**
 * Servlet implementation class LongdescServlet
 */
public class LongdescServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(LongdescServlet.class);
	private static ArquivoDao arquivoDao = ArquivoDaoSpring.getInstance();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LongdescServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			File f = new File(request.getRequestURI());
			String arr[] = f.getName().split("-");
			Long id = Long.valueOf(arr[arr.length-1].split("\\.")[0]);
			
			Arquivo arquivo = arquivoDao.select(id);
			if(arquivo!=null){
				StringBuilder sb = new StringBuilder();
				sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n")
				.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"pt-br\" lang=\"pt-br\">\n")
				.append("<head><title>")
				.append(arquivo.getDeArquivo())
				.append("</title>\n")
				.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=iso-8859-1\" />")
				.append("<meta name=\"language\" content=\"pt-br\" />")
				.append("</head>")
				.append("<body><div>")
				.append(arquivo.getLongdesc())
				.append("</div></body></html>");
				PrintWriter pw = response.getWriter();
				pw.write(sb.toString());
				pw.close();
			}else{//not found
				response.setStatus(404);
			}
		}catch(Exception e){
			logger.error("Erro ao gerar long desc.",e);
			throw new ServletException();
		}
	}

}
